package com.ququ.syb.business.withdraw.service;

import com.alibaba.fastjson.JSON;
import com.ququ.common.result.Result;
import com.ququ.common.result.ResultJson;
import com.ququ.syb.business.withdraw.fegin.*;
import com.ququ.syb.business.withdraw.rabbitmq.RabbitMQSender;
import com.ququ.syb.common.constant.*;
import com.ququ.syb.common.pojo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WithdrawOrderService {
    @Autowired
    private WithdrawOrderFegin withdrawOrderFegin;
    @Autowired
    private BankCardFegin bankCardFegin;
    @Autowired
    private CommissionFegin commissionFegin;
    @Autowired
    private PayChannelFegin payChannelFegin;
    @Autowired
    private BalanceFegin balanceFegin;
    @Autowired
    private PayOrderFegin payOrderFegin;
    @Autowired
    private ChannelsRouterFegin channelsRouterFegin;
    @Autowired
    private RabbitMQSender rabbitMQSender;

    private static final String DIRECT_CLRAR_PREFIX = "DCAW-";
    private static final String DIRECT_VIRTUAL_PREFIX = "DCVW-";

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");

    /**
     * 创建普通提现订单（来自p1001）
     */
    public Result<WithdrawOrder> createWithdrawOrder(String accountid,String tradenum,String outordernum,Long amount,String paychannelid,String appcode,Integer type,Integer withdrawtype,String callbackurl,String paytradenum){
        Result<WithdrawOrder> withdrawOrderResult = withdrawOrderFegin.queryWithdrawOrderByOutOrderNum(outordernum);
        if (withdrawOrderResult.getStatus()==ResultStatusConstant.SUCCESS)
            return new Result<>(-1,"外部订单号重复");
        PayChannel payChannel = payChannelFegin.getPayChannel(paychannelid,accountid,appcode).getData();
        if (payChannel == null)
            return new Result<>(-1,"通道不可用或子商户未开通此通道");
        if (payChannel.getAllowwithdraw() != null && payChannel.getAllowwithdraw() != 1 && type != WithdrawOrderTypeConstant.WITHDRAW)
            return new Result<>(-1,"本通道不支持外部提现");
        AccountChannelBalance accountChannelBalance = balanceFegin.getAccountChannelBalance(accountid,paychannelid).getData();
        if (amount > accountChannelBalance.getBalance())
            return new Result<>(-1,accountid+"的"+paychannelid+"通道账户余额:"+accountChannelBalance.getBalance()/100d+"元，余额不足");
        BankAccountInfo bankAccountInfo = bankCardFegin.getBankAccountInfo(accountid).getData();
        if (bankAccountInfo == null)
            return new Result<>(-1,"本账户未绑定提现卡，无法提现");
        Long customerCommission = commissionFegin.getWithdrawCommission(amount, paychannelid, appcode, accountid).getData();
        Long costCommission = commissionFegin.getWithdrawCostCommission(amount, paychannelid, withdrawtype).getData();
        //开始创建提现订单
        WithdrawOrder withdrawOrder = new WithdrawOrder();
        if (StringUtils.isNotBlank(tradenum))
            withdrawOrder.setTradenum(tradenum);
        withdrawOrder.setOutordernum(outordernum);
        withdrawOrder.setAccountid(accountid);
        withdrawOrder.setAmount(amount);
        withdrawOrder.setAppcode(appcode);
        withdrawOrder.setPaychannelid(paychannelid);
        withdrawOrder.setCustomercommission(customerCommission);
        withdrawOrder.setCommission(costCommission);
        withdrawOrder.setPaytradenum(paytradenum);
        withdrawOrder.setBankaccountname(bankAccountInfo.getBankaccountname());
        withdrawOrder.setBankcardno(bankAccountInfo.getBankaccountno());
        withdrawOrder.setBankcardid(bankAccountInfo.getId());
        withdrawOrder.setBankname(bankAccountInfo.getBankname());
        withdrawOrder.setType(type);
        withdrawOrder.setWithdrawtype(withdrawtype);
        withdrawOrder.setCallbackurl(callbackurl);
        withdrawOrder.setStatus(WithdrawStatusConstant.AUDIT_SUCCESS);
        withdrawOrder = withdrawOrderFegin.saveWithdrawOrder(withdrawOrder).getData();
        return new Result<>(withdrawOrder);
    }

    /**
     * 创建伪直清提现订单
     */
    public Result<WithdrawOrder> createDirectClearWithdrawOrder(String paytradenum){
        PayOrder payOrder = payOrderFegin.getPayOrder(paytradenum).getData();
        if (payOrder == null)
            return new Result<>(-1,paytradenum+"支付订单不存在，无法创建直清提现订单");
        if (payOrder.getStatus() != PayOrderStatusConstant.SUCCESS)
            return new Result<>(-1,paytradenum+"支付订单不是成功状态，无法创建直清提现订单");
        PayChannel payChannel = payChannelFegin.getPayChannel(payOrder.getPaychannelid()).getData();
        if (payChannel.getIsAutoClear() != PayChannelClearTypeConstant.FAKE_DIRECT_CLEAR)
            return new Result<>(-1,"本通道不是伪直清通道，不允许创建直清提现订单");
        List<WithdrawOrder> withdrawOrderList = withdrawOrderFegin.listWithdrawOrderByPayTradenum(paytradenum).getData();
        Integer suffix = withdrawOrderList==null?1:withdrawOrderList.size()+1;
        if (withdrawOrderList != null && withdrawOrderList.size()>1){
            for (WithdrawOrder withdrawOrder: withdrawOrderList){
                if (withdrawOrder.getStatus() == WithdrawStatusConstant.SUCCESS)
                    return new Result<>(-1,paytradenum+"伪直清提现订单"+withdrawOrder.getTradenum()+"已经成功，无需重复提现");
                else {
                    //查询提现订单
                    ResultJson queryWithdrawResult = channelsRouterFegin.queryWithdraw(withdrawOrder.getAccountid(),withdrawOrder.getPaychannelid(),withdrawOrder.getTradenum());
                    if (queryWithdrawResult.getStatus() == ResultStatusConstant.SUCCESS){
                        Map<String,Object> queryResultMap = (Map<String, Object>) queryWithdrawResult.getData();
                        if (queryResultMap.containsKey("withdrawStatus") && Integer.parseInt(queryResultMap.get("withdrawStatus").toString()) == WithdrawStatusConstant.SUCCESS){
                            //将提现订单改成成功
                            Map<String,Object> map = new HashMap<>();
                            map.put("tradenum", withdrawOrder.getTradenum());
                            map.put("status", 1);
                            map.put("failreason", "交易成功");
                            map.put("fakecallback",0);  //模拟回调
                            rabbitMQSender.send(RabbitMqQueueNameConstant.WITHDRAW_CALLBACK, JSON.toJSONString(map));
                            //退出
                            return new Result<>(-1,paytradenum+"伪直清提现订单"+withdrawOrder.getTradenum()+"已经成功，无需重复提现");
                        }
                    }
                }
            }
        }
        String outordernum = paytradenum+suffix;
        String tradenum = DIRECT_CLRAR_PREFIX+outordernum;
        Integer withdrawtype = WithdrawTypeConstant.D0;
        if (payChannel.getWithdrawcommissiontype() == 2 && !simpleDateFormat.format(new Date()).equals(simpleDateFormat.format(payOrder.getCreatetime())))
            withdrawtype = WithdrawTypeConstant.D1;
        return createWithdrawOrder(payOrder.getPayeeaccount(),
                tradenum,
                outordernum,
                payOrder.getAmount()-payOrder.getPayeecommission(),
                payOrder.getPaychannelid(),
                payOrder.getAppcode(),
                WithdrawOrderTypeConstant.DIRECT_CLEAR,
                withdrawtype,
                payOrder.getWithdrawcallbackurl(),
                paytradenum
                );
    }

    /**
     * 创建直清虚拟提现订单
     */

    public Result<WithdrawOrder> createDirectVirtualWithdrawOrder(String paytradenum){
        PayOrder payOrder = payOrderFegin.getPayOrder(paytradenum).getData();
        if (payOrder == null)
            return new Result<>(-1,paytradenum+"支付订单不存在，无法创建直清提现订单");
        if (payOrder.getStatus() != PayOrderStatusConstant.SUCCESS)
            return new Result<>(-1,paytradenum+"支付订单不是成功状态，无法创建直清提现订单");
        PayChannel payChannel = payChannelFegin.getPayChannel(payOrder.getPaychannelid()).getData();
        if (payChannel.getIsAutoClear() != PayChannelClearTypeConstant.REAL_DIRECT_CLEAR)
            return new Result<>(-1,"本通道不是直清通道，不允许创建虚拟提现订单");
        List<WithdrawOrder> withdrawOrderList = withdrawOrderFegin.listWithdrawOrderByPayTradenum(paytradenum).getData();
        Integer suffix = withdrawOrderList==null?1:withdrawOrderList.size()+1;
        if (withdrawOrderList != null && withdrawOrderList.size()>1){
            return new Result<>(-1,paytradenum+"订单虚拟提现订单已经创建，无需重复创建");
        }
        String outordernum = paytradenum+suffix;
        String tradenum = DIRECT_VIRTUAL_PREFIX+outordernum;
        Integer withdrawtype = WithdrawTypeConstant.D0;
        return createWithdrawOrder(payOrder.getPayeeaccount(),
                tradenum,
                outordernum,
                payOrder.getAmount()-payOrder.getPayeecommission(),
                payOrder.getPaychannelid(),
                payOrder.getAppcode(),
                WithdrawOrderTypeConstant.VIRTUAL_WITHDRAW,
                withdrawtype,
                payOrder.getWithdrawcallbackurl(),
                paytradenum
        );
    }


}
